import 'dart:async';

import 'package:get/get.dart';

enum CountDownMode { sleep, action }


class TimerManager {

  TimerManager._internal();

  static final TimerManager _singleton = TimerManager._internal();

  factory TimerManager() => _singleton;

  Timer? _timer;
  RxnInt actionTime = RxnInt(-1);

  int? actionTimeCountdown;

  void setCountDownTime({int? actionTimeCountdown}){
    this.actionTimeCountdown = actionTimeCountdown;
  }


  void startCountDown(CountDownMode mode,callback,{bool reset = true}){
    cancel();
    int countTime = 0;
    if(reset){

      if(mode == CountDownMode.action){
        countTime = actionTimeCountdown??60;
      }
      setTime(mode,countTime);
    }else{
      if(mode == CountDownMode.action){
        countTime = actionTime.value??60;
      }
    }
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countTime <= 0) {
        callback();
        _timer?.cancel();
        _timer = null;
        return;
      }
      countTime--;
      setTime(mode,countTime);
      print('mode = $mode ,countTime=$countTime');
    });
  }

  setTime(mode, countTime){
    if(mode == CountDownMode.action){
      actionTime.value = countTime;
    }
  }

  void cancel(){
    if(_timer != null){
      if (_timer!.isActive) {
        _timer!.cancel();
        _timer = null;
      }
    }
  }

}
